import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../common/index.dart';

class ChatListController extends GetxController with WidgetsBindingObserver {
  ChatListController();

  // 当前用户ID
  String? current_user_id;

  // 聊天列表数据
  final RxList<ChatListItem> chat_list_items = <ChatListItem>[].obs;

  // 从ChatService获取聊天数据并处理成聊天列表项
  Future<void> _init_data() async {
    debugPrint('正在加载聊天列表数据');
    // 获取当前用户
    current_user_id = UserService().get_now_user()?.id;
    if (current_user_id == null) {
      debugPrint('用户未登录');
      return;
    }

    // 获取所有可见的聊天（考虑部分隐藏的聊天记录）
    final Map<String, List<ChatModel>> visibleChatsMap = await ChatService.to
        .get_all_user_visible_chats(current_user_id!);

    // 为每个对话创建一个聊天列表项
    List<ChatListItem> items = [];

    for (var entry in visibleChatsMap.entries) {
      final String other_user_id = entry.key;
      final List<ChatModel> chats = entry.value;

      // 如果没有消息，跳过
      if (chats.isEmpty) continue;

      // 获取最后一条消息
      final last_message = chats.reduce(
        (a, b) =>
            DateTime.parse(a.created_time).isAfter(DateTime.parse(b.created_time))
            ? a
            : b,
      );

      // 获取未读消息数量
      int unread_count = chats
          .where(
            (chat) => chat.receive_user_id == current_user_id && !chat.is_reading,
          )
          .length;

      // 获取用户信息
      final user = UserService().get_user_data_by_id(other_user_id);

      if (user != null) {
        items.add(
          ChatListItem(
            user_id: other_user_id,
            name: user.name ?? 'Unknown',
            avatar: user.avatar_image ?? '',
            last_message: last_message.detail,
            last_message_time: last_message.created_time,
            unread_count: unread_count,
          ),
        );
      }
    }

    // 按最后消息时间排序
    items.sort(
      (a, b) => DateTime.parse(
        b.last_message_time,
      ).compareTo(DateTime.parse(a.last_message_time)),
    );

    chat_list_items.value = items;

    debugPrint('聊天列表初始化完成: ${chat_list_items.length}个会话');
    update(["chat_list"]);
  }

  // 跳转到聊天详情页
  void navigate_to_chat_detail(String userId) {
    debugPrint('跳转到与用户$userId的聊天');
    RouteUtil.push(RouteNames.chat, extra: {'userId': userId}).then((_) {
      // 从聊天详情页返回后，刷新聊天列表
      debugPrint('从聊天页面返回，刷新聊天列表数据');
      _init_data();
    });
  }

  // 刷新聊天列表数据
  Future<void> refresh_chat_list() async {
    await _init_data();
  }

  @override
  void onInit() {
    super.onInit();
    // 注册应用生命周期观察者
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void onReady() {
    super.onReady();
    _init_data();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 当应用从后台恢复到前台时刷新数据
    if (state == AppLifecycleState.resumed) {
      debugPrint('应用回到前台，刷新聊天列表数据');
      _init_data();
    }
  }

  @override
  void onClose() {
    // 移除应用生命周期观察者
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
  }
}

// 聊天列表项数据模型
class ChatListItem {
  final String user_id;
  final String name;
  final String avatar;
  final String last_message;
  final String last_message_time;
  final int unread_count;

  ChatListItem({
    required this.user_id,
    required this.name,
    required this.avatar,
    required this.last_message,
    required this.last_message_time,
    required this.unread_count,
  });

  // 格式化时间
  String get formatted_time {
    final DateTime message_time = DateTime.parse(last_message_time);
    final DateTime now = DateTime.now();

    if (message_time.year == now.year &&
        message_time.month == now.month &&
        message_time.day == now.day) {
      // 今天的消息，只显示时间
      return '${message_time.hour.toString().padLeft(2, '0')}:${message_time.minute.toString().padLeft(2, '0')}';
    } else {
      // 不是今天的消息，显示月日
      return '${message_time.month}/${message_time.day}';
    }
  }
}
